using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;

namespace Lzfy_His_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class RoleController : ControllerBase
    {
        private readonly IRoleService _roleService;
        private readonly ILogger<RoleController> _logger;

        public RoleController(IRoleService roleService, ILogger<RoleController> logger)
        {
            _roleService = roleService;
            _logger = logger;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        [HttpPost("list")]
        public async Task<IActionResult> GetRoleList([FromBody] RoleListRequest request)
        {
            try
            {
                var result = await _roleService.GetRoleListAsync(request);
                return Ok(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色列表失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取角色详情
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetRoleById(int id)
        {
            try
            {
                var role = await _roleService.GetRoleByIdAsync(id);
                if (role == null)
                {
                    return NotFound(new { success = false, message = "角色不存在" });
                }
                return Ok(new { success = true, data = role });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色详情失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateRole([FromBody] RoleDto roleDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var roleId = await _roleService.CreateRoleAsync(roleDto);
                return Ok(new { success = true, data = new { id = roleId }, message = "角色创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建角色失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateRole(int id, [FromBody] RoleDto roleDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var result = await _roleService.UpdateRoleAsync(id, roleDto);
                if (result)
                {
                    return Ok(new { success = true, message = "角色更新成功" });
                }
                return BadRequest(new { success = false, message = "角色更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新角色失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRole(int id)
        {
            try
            {
                var result = await _roleService.DeleteRoleAsync(id);
                if (result)
                {
                    return Ok(new { success = true, message = "角色删除成功" });
                }
                return BadRequest(new { success = false, message = "角色删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除角色失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 切换角色状态
        /// </summary>
        [HttpPost("{id}/toggle-status")]
        public async Task<IActionResult> ToggleRoleStatus(int id, [FromBody] ToggleStatusRequest request)
        {
            try
            {
                var result = await _roleService.ToggleRoleStatusAsync(id, request.IsActive);
                if (result)
                {
                    return Ok(new { success = true, message = "角色状态更新成功" });
                }
                return BadRequest(new { success = false, message = "角色状态更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换角色状态失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有激活的角色
        /// </summary>
        [HttpGet("active")]
        public async Task<IActionResult> GetAllActiveRoles()
        {
            try
            {
                var roles = await _roleService.GetAllActiveRolesAsync();
                return Ok(new { success = true, data = roles });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取激活角色列表失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 分配角色权限
        /// </summary>
        [HttpPost("{id}/permissions")]
        public async Task<IActionResult> AssignRolePermissions(int id, [FromBody] List<int> menuIds)
        {
            try
            {
                var request = new RolePermissionRequest
                {
                    RoleId = id,
                    MenuIds = menuIds
                };

                var result = await _roleService.AssignRolePermissionsAsync(request);
                if (result)
                {
                    return Ok(new { success = true, message = "角色权限分配成功" });
                }
                return BadRequest(new { success = false, message = "角色权限分配失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分配角色权限失败，角色ID: {RoleId}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取角色权限
        /// </summary>
        [HttpGet("{id}/permissions")]
        public async Task<IActionResult> GetRolePermissions(int id)
        {
            try
            {
                var permissions = await _roleService.GetRolePermissionsAsync(id);
                return Ok(new { success = true, data = permissions });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色权限失败，角色ID: {RoleId}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }
    }
}